﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin;
using CCWin.SkinControl;
using System.IO;
using System.Threading;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace SafeSave
{
    public partial class MainForm : CCSkinMain
    {
        //临时
        string fileaddress;
        //http请求相关
        HttpHelper httphelper = new HttpHelper();//http辅助类
        string req;//请求内容
        bool canrequest = true;

        //用户信息
        private ChatListSubItem userItem;
        private UserData user;


        //文件信息
        private FileMessage downloadFiles = new FileMessage();

        byte[] file;//上传的文件



        //联系人信息
        private List<ChatListSubItem> contacts = new List<ChatListSubItem>();//联系人

        
        public MainForm(string address,string url)
        {
            InitializeComponent();
            this.userItem = new ChatListSubItem();
            user = new UserData(this.userItem);
            User.user = this.user;
            User.user.account_address = address;
            User.user.url = url;
            this.timerCheckRequest.Enabled = true;
            this.timerCheckRequest.Start();
        }

        //加载
        private void MainForm_Load(object sender, EventArgs e)
        {
            /**********************这里是虚假信息********************************/
            string[] temp = { "fate stay night", "fate grand order" };
            User.user.uploadsFiles.fileNum = 2;
            User.user.uploadsFiles.fileNames.AddRange(temp);
            User.user.downloadFiles.fileNum = 2;
            User.user.downloadFiles.fileNames.AddRange(temp);
            User.user.item.NicName = "阿尔托莉雅";

            /**********************这里是虚假信息********************************/
            //加载个人信息
            this.privateKeyBox.Text = User.user.account_address;//用户私钥
            this.userNameBox.Text = User.user.item.NicName;//显示用户名

            //加载下载文件
           
            this.downloadFiles = getDownloadFiles();
            //List<string> uploadFiles = getUploadFiles();
            //this.showFiles(uploadFiles);

            string res = httphelper.HttpGet("http://" + User.user.url + "/all_DOs", "");//返回的Json
            List<string> ownerAddress = new List<string>();
            if(res!=null)
            {
                JArray ja = JArray.Parse(res);

                //JObject jo = JObject.Parse(res);
                ownerAddress = ja.ToObject<List<string>>();
            }
            //加载好友
            for (int i = 0; i < ownerAddress.ToArray().Length; i++)
            {
                ChatListSubItem tempContact = new ChatListSubItem();
                tempContact.ID = (uint)i;
                tempContact.DisplayName = ownerAddress[i].ToString();
                contacts.Add(tempContact);
            }
            friendlist.Items[0].SubItems.AddRange(contacts.ToArray());

            

        }

        //获取上传的文件
        private List<string> getUploadFiles()
        {
            string res = httphelper.HttpGet("http://" + User.user.url + "/all_file_names", "");//返回的Json

            List<string> fileNames = new List<string>();
            if (res != null)
            {
                JArray ja = JArray.Parse(res);

                //JObject jo = JObject.Parse(res);
                fileNames = ja.ToObject<List<string>>();
            }
            return fileNames;
        }
        //获取下载的文件
        private FileMessage getDownloadFiles()
        {
            //此处需要更改
            FileMessage downLoadFiles = User.user.downloadFiles;
            return downLoadFiles;
        }
        //展示文件
        private void showFiles(List<string> upLoadFiles)
        {
            uploadFileBox.Items.Clear();
            //显示上传文件
            for (int i = 0; i < upLoadFiles.Count; i++)
            {
                SkinListBoxItem tempFile = new SkinListBoxItem();
                tempFile.Text = upLoadFiles[i];
                uploadFileBox.Items.Add(tempFile);
            }
            //显示下载文件
            downloadFileBox.Items.Clear();
            for (int i = 0; i < this.downloadFiles.fileNum; i++)
            {
                SkinListBoxItem tempFile = new SkinListBoxItem();
                tempFile.Text = downloadFiles.fileNames[i];
                downloadFileBox.Items.Add(tempFile);
            }
        }

        //双击好友
        private void friendlist_DoubleClickSubItem(object sender, ChatListEventArgs e, MouseEventArgs es)
        {
            ChatListSubItem item = e.SelectSubItem;
            item.IsTwinkle = false;

            //ipSend为从列表中取出，要发送的对象的IP
            string ipSend = item.IpAddress;
            string nameSend = item.DisplayName;
            string idSend = item.NicName;
            string mesSend = string.Empty;
            contactImg.BackgroundImage = item.HeadImage;
            contactNameLabel.Text = item.DisplayName;

            this.ownerid.Text = item.DisplayName;

            string res = httphelper.HttpGet("http://" + User.user.url + "/all_DOs", "");//返回的Json
            List<string> ownerAddress = new List<string>();
            if (res != null)
            {
                JArray ja = JArray.Parse(res);

                //JObject jo = JObject.Parse(res);
                ownerAddress = ja.ToObject<List<string>>();
            }
            contacts.Clear();
            //加载好友
            for (int i = 0; i < ownerAddress.ToArray().Length; i++)
            {
                ChatListSubItem tempContact = new ChatListSubItem();
                tempContact.ID = (uint)i;
                tempContact.DisplayName = ownerAddress[i].ToString();
                contacts.Add(tempContact);
            }
            friendlist.Items[0].SubItems.Clear();
            friendlist.Items[0].SubItems.AddRange(contacts.ToArray());

        }
        
        //点击申请按钮
        private void sendButton_Click(object sender, EventArgs e)
        {
            //byte[] tempIP = System.Text.Encoding.UTF8.GetBytes(targetIPBox.Text);
            //string targetIP = Convert.ToBase64String(tempIP);
            byte[] tempMsg = System.Text.Encoding.UTF8.GetBytes(exMsgBox.Text);
            string extraMessage = Convert.ToBase64String(tempMsg);

            SendRegistrationJobject sendRegistrationJobject = new SendRegistrationJobject();
            //sendRegistrationJobject.target_ip = targetIP;
            sendRegistrationJobject.target_ip = targetIPBox.Text;
            sendRegistrationJobject.extra_message = extraMessage;

            req = JsonConvert.SerializeObject(sendRegistrationJobject);//创建请求Json
            httphelper.HttpPost("http://" + User.user.url + "/DU_send_registration_request", req);//返回的Json
        }
        
        //选择文件
        private void ChooseFile()
        {
            try
            {
                OpenFileDialog dia = new OpenFileDialog();
            }
            catch
            {
                MessageBox.Show("文件打开失败！" + "\r\n");
            }
        }
        //点击选择文件
        private void chooseFileButton_Click(object sender, EventArgs e)
        {
            
            ChooseFile();
        }


/*********************************文件管理部分****************************/
        //为文件选择标签
        void chooseFileTags(List<string> fileTags,List<string> policy)
        {

            for(int i=0;i<fileTags.ToArray().Length;i++)
            {
                SkinListBoxItem tempItem = new SkinListBoxItem();
                tempItem.Text = fileTags[i];
                tagBox.Items.Add(tempItem);
            }
            for (int i = 0; i < policy.ToArray().Length; i++)
            {
                SkinListBoxItem tempItem = new SkinListBoxItem();
                tempItem.Text = policy[i];
                policyBox.Items.Add(tempItem);
            }
        }
        //按下打开文件按钮
        private void openFileButton_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog Dlg = new OpenFileDialog();
                Dlg.CheckFileExists = true;
                Dlg.InitialDirectory = "C:\\Documents and Settings\\" + System.Environment.UserName + "\\桌面\\";
                if (Dlg.ShowDialog() == DialogResult.OK)
                {
                    //Thread t = new Thread(readFile);
                    //t.Start(Dlg.FileName.ToString());
                    FileStream fs = new FileStream(Dlg.FileName.ToString(),FileMode.Open);
                    file = new byte[fs.Length];
                    int start = 0;
                    long end = fs.Length;
                    int num;

                    while (end > 0)
                    {
                        fs.Position = start;
                        if (end > 1024)
                            num = fs.Read(file, start, 1024);//读取文件
                        else num = num = fs.Read(file, start, (int)end);

                        if (num == 0)
                            break;
                        start += num;
                        end -= num;

                        fileOpenBar.Value = (int)(((float)start / (float)fs.Length) * 100);
                    }
                    filenameLabel.Text = Path.GetFileName(Dlg.FileName);
                    fs.Close();
                    fs.Dispose();

                    TagChooseForm tagChooseForm = new TagChooseForm();
                    tagChooseForm.chooseFileTags += new TagChooseForm.chooseTags(chooseFileTags);
                    tagChooseForm.Show();
                }
            }
            catch
            {
                MessageBox.Show("打开文件失败");
            }
        }
        //按下上传按钮
        private void uploadButton_Click(object sender, EventArgs e)
        {
            try
            {
                //准备请求内容
                //文件标签
                List<string> tags = new List<string>();
                for (int i = 0; i < tagBox.Items.Count; i++)
                {
                    byte[] temp_tag = System.Text.Encoding.UTF8.GetBytes(tagBox.Items[i].Text);//tag转为byte
                    tags.Add(Convert.ToBase64String(temp_tag));//tag转为base64
                }
                //文件策略
                List<string> policys = new List<string>();
                for (int i = 0; i < tagBox.Items.Count; i++)
                {
                    byte[] temp_policy = System.Text.Encoding.UTF8.GetBytes(policyBox.Items[i].Text);//policy转为byte
                    policys.Add(Convert.ToBase64String(temp_policy));//policy转为base64
                }
                //文件内容
                string fileContent = Convert.ToBase64String(file);
                //文件名
                byte[] temp_name = System.Text.Encoding.UTF8.GetBytes(filenameLabel.Text);//文件名转为byte

                UploadFileJobject fileuploadobj = new UploadFileJobject();
                fileuploadobj.content = Convert.ToBase64String(file);
                fileuploadobj.file_name = Convert.ToBase64String(temp_name);
                fileuploadobj.keywords = tags;
                fileuploadobj.policy = policys;

                req = JsonConvert.SerializeObject(fileuploadobj);//创建请求Json
                string res = httphelper.HttpPost("http://"+User.user.url + "/upload_file", req);//返回的Json

                JObject jo = JObject.Parse(res);//返回的Json转为类
                fileaddress = jo.GetValue("transaction_id").ToString();

                MessageBox.Show("文件上传成功");
            }
            catch
            {
                MessageBox.Show("文件上传失败！");
            }
            tagBox.Items.Clear();
            policyBox.Items.Clear();
            filenameLabel.Text = "请选择文件";
            
            ////重新获取上传历史
            //List<string> uploadFiles = getUploadFiles();
            //this.showFiles(uploadFiles);
        }

        //按下下载按钮
        private void downloadFileButton_Click(object sender, EventArgs e)
        {
            if(uploadFileBox.SelectedItem!=null)
            {
                string fileid = fileaddress;//uploadFiles.fileID[uploadFileBox.SelectedIndex];
                try
                {
                    DownloadFileJobject fieldownloadobj = new DownloadFileJobject();
                    fieldownloadobj.transaction_id = fileid; 

                    req = JsonConvert.SerializeObject(fieldownloadobj);//创建请求Json
                    string res = httphelper.HttpPost("http://"+User.user.url + "/download_file", req);//返回的Json

                    JObject jo = JObject.Parse(res);//返回的Json转为类
                    string filecontent_receive = jo.GetValue("content").ToString();

                    SaveFileDialog Dlg = new SaveFileDialog();
                    Dlg.InitialDirectory = "C:\\Documents and Settings\\" + System.Environment.UserName + "\\桌面\\";
                    if (Dlg.ShowDialog() == DialogResult.OK)
                    {
                        FileStream fs = new FileStream(Dlg.FileName.ToString(), FileMode.Create);
                        byte[] content = Convert.FromBase64String(filecontent_receive);
                        fs.Write(content,0,content.Length);
                        fs.Close();
                    }
                }
                catch
                {
                    MessageBox.Show("文件下载失败");
                }
                MessageBox.Show("文件下载成功");
            }
            else
            {
                MessageBox.Show("请先选择文件");
            }
        }

        public void continueSendRequests()
        {
            canrequest = true;
        }

        private void timerCheckRequest_Tick(object sender, EventArgs e)
        {
            if(canrequest)
            {
                try
                {

                    string res = httphelper.HttpGet("http://" + User.user.url + "/all_registrations", "");//返回的Json

                    if (res != "")
                    {
                        JObject jo = JObject.Parse(res);//返回的Json转为类
                        string address = jo.GetValue("address").ToString();
                        string time = jo.GetValue("time").ToString();
                        string ex_msg = jo.GetValue("ex_msg").ToString();
                        
                        ApplyRightForm applyRightform = new ApplyRightForm(address, time, ex_msg);
                        canrequest = false;
                        applyRightform.continueSendRequest += new ApplyRightForm.continueRequest(continueSendRequests);
                        applyRightform.ShowDialog(this);
                    }

                }
                catch
                {
                    MessageBox.Show("定时接收请求失败");
                }
            }
            
        }

        private void searchButton_Click(object sender, EventArgs e)
        {
            List<string> keywords = new List<string>();
            List<string> searchWords = new List<string>();
            string inputs = searchBox.Text;
            keywords = inputs.Split(' ').ToList<string>();

            SearchJobject searchJobject = new SearchJobject();
            searchJobject.account_address = ownerid.Text;

            for (int i = 0; i < keywords.Count; i++)
            {
                byte[] temp_keywords = System.Text.Encoding.UTF8.GetBytes(keywords[i]);//policy转为byte
                searchWords.Add(Convert.ToBase64String(temp_keywords));//policy转为base64
            }

            searchJobject.tokens = searchWords;
            req = JsonConvert.SerializeObject(searchJobject);//创建请求Json 

            string res = httphelper.HttpPost("http://" + User.user.url + "/search", req);//返回的Json

            JArray ja = JArray.Parse(res);
            List<string> searchedFiles = new List<string>();
            searchedFiles = ja.ToObject<List<string>>();

            searchFileBox.Items.Clear();

            if (res!=null)
            {
                //显示上传文件
                for (int i = 0; i < searchedFiles.Count; i++)
                {
                    SkinListBoxItem tempFile = new SkinListBoxItem();
                    tempFile.Text = searchedFiles[i];
                    searchFileBox.Items.Add(tempFile);
                }
            }
            
        }

        private void downloadButton_Click(object sender, EventArgs e)
        {
            if (searchFileBox.SelectedItem != null)
            {
                string fileid = searchFileBox.Items[searchFileBox.SelectedIndex].Text;
                try
                {
                    DownloadFileJobject fieldownloadobj = new DownloadFileJobject();
                    fieldownloadobj.transaction_id = fileid;

                    req = JsonConvert.SerializeObject(fieldownloadobj);//创建请求Json
                    string res = httphelper.HttpPost("http://" + User.user.url + "/download_file", req);//返回的Json

                    JObject jo = JObject.Parse(res);//返回的Json转为类
                    string filecontent_receive = jo.GetValue("content").ToString();

                    SaveFileDialog Dlg = new SaveFileDialog();
                    Dlg.InitialDirectory = "C:\\Documents and Settings\\" + System.Environment.UserName + "\\桌面\\";
                    if (Dlg.ShowDialog() == DialogResult.OK)
                    {
                        FileStream fs = new FileStream(Dlg.FileName.ToString(), FileMode.Create);
                        byte[] content = Convert.FromBase64String(filecontent_receive);
                        fs.Write(content, 0, content.Length);
                        fs.Close();
                    }
                }
                catch
                {
                    MessageBox.Show("文件下载失败");
                }
            }
            else
            {
                MessageBox.Show("请先选择文件");
            }
        }


        /*********************************文件管理部分****************************/
    }
}
